package com.ayoka.mvp;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.ViewGroup;

import com.ayoka.Constant;
import com.ayoka.R;
import com.ayoka.base.BasePresenter;
import com.ayoka.base.IBaseView;
import com.ayoka.bean.BaseResponse;
import com.ayoka.bean.CourseBean;
import com.ayoka.bean.CourseBean.InteractiveQuestionBean;
import com.ayoka.bean.MusicFileBean;
import com.ayoka.database.DBManager;
import com.ayoka.download.DownloadService;
import com.ayoka.download.SimpleDownloadCalback;
import com.ayoka.http.API;
import com.ayoka.http.OkHttpListener;
import com.ayoka.mvp.CourseMVP.CourseModel.ResponseCourseDetailBean;
import com.ayoka.ui.course.detail.CourseDetailActivity;
import com.ayoka.ui.course.detail.CourseDetailMessageOptionDialog;
import com.ayoka.ui.course.detail.CourseDetailQuestionDialog;
import com.ayoka.ui.course.detail.CourseDetailTextDialog;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.jcp.baselibrary.dialog.BaseDialogFragment;
import com.jcp.baselibrary.dialog.DialogDismissListener;
import com.jcp.baselibrary.dialog.DialogResultListener;
import com.jcp.baselibrary.permission.MPermission;
import com.jcp.baselibrary.utils.UIUtils;

import java.io.File;

/**
 * Created by gabriel on 2017/3/5.
 */

public interface CourseMVP {

    interface CourseModel {

        class ResponseCourseDetailBean {
            public CourseBean course;
            public long record_id;
        }

    }

    interface ICourseView extends IBaseView {

        void configCourseDetailData(ResponseCourseDetailBean courseBean);

        void onUpdateCourseCompletedStatusSuccess();

        void onMessageOptionSelected(long questionId, int optionIndex);

        void onCancelCollectionCourseSuccess();

        void onCollectionCourseSuccess();

        void onDownloadSuccess(String filePath);

        void onDownloadStart();

        void onCourseTextDialogDismiss();
    }

    class CoursePresenter extends BasePresenter<ICourseView> {

        // 下载服务
        private DownloadService.DownloadBinder downloadBinder;

        private Activity activity;

        private ServiceConnection connection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                downloadBinder = (DownloadService.DownloadBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        // 下载文件md5
        private Md5FileNameGenerator fileNameGenerator;

        public CoursePresenter(Activity activity) {
            this.activity = activity;
            fileNameGenerator = new Md5FileNameGenerator();
        }

        @Override
        public void attach(ICourseView view) {
            super.attach(view);
            if (activity != null) {
                //启动服务可以保证DownloadService一直在后台运行
                Intent intent = new Intent(activity, DownloadService.class);
                //进行通信，因此两个方法的调用都必不可少。
                activity.startService(intent);  //启动服务
                activity.bindService(intent, connection, Activity.BIND_AUTO_CREATE);//绑定服务
            }
        }

        public Md5FileNameGenerator getFileNameGenerator() {
            return fileNameGenerator;
        }

        public void getCourseDetailData(long courseId) {
            mViewRef.get().showWaitDialog(UIUtils.getString(R.string.loading));
            API.getCourseDetailData(this, courseId, new OkHttpListener<BaseResponse<ResponseCourseDetailBean>>() {
                @Override
                public void onSuccess(BaseResponse<ResponseCourseDetailBean> response) {
                    if (!isAttached()) return;
                    mViewRef.get().hideWaitDialog();
                    mViewRef.get().configCourseDetailData(response.data);
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                    if (!isAttached()) return;
                    mViewRef.get().hideWaitDialog();
                    mViewRef.get().showToast(errorMessage);
                }
            });
        }

        public void showMessageOptionDialog(FragmentManager fragmentManager, final InteractiveQuestionBean courseMessageOption, long duration) {
            final CourseDetailMessageOptionDialog dialog = new CourseDetailMessageOptionDialog.Builder()
                    .setOutCancel(false)
                    .setBackgroundLevel(0)
                    .setGravity(Gravity.BOTTOM)
                    .setAnimation(R.style.SlideBottomAnimation)
                    .setSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    .setTitle(courseMessageOption.Question)
                    .setOptionData(courseMessageOption.Options)
                    .setDuration(duration)
                    .build();
            dialog.setDialogResultListener(new DialogResultListener<CourseBean.OptionBean>() {
                @Override
                public void result(BaseDialogFragment dialogFragment, CourseBean.OptionBean optionBean) {
                    dialogFragment.dismissAllowingStateLoss();
                    if (!isAttached()) return;
                    mViewRef.get().onMessageOptionSelected(courseMessageOption.ID, optionBean.Index);
                }
            });
            dialog.show(fragmentManager, "CourseDetailMessageOptionDialog");
        }

        public void UpdateCourseCompletedStatus(long courseId, long record_id) {
            API.UpdateCourseCompletedStatus(this, courseId, record_id, new OkHttpListener<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse response) {
                    if (!isAttached()) return;
                    mViewRef.get().onUpdateCourseCompletedStatusSuccess();
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                    if (!isAttached()) return;
                    mViewRef.get().showToast(errorMessage);
                }
            });
        }

        public void AddCourseInteractiveAnswer(long record_id, long courseId, long questionId, int optionIndex) {
            API.AddCourseInteractiveAnswer(this, courseId, record_id, questionId, optionIndex, new OkHttpListener<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse response) {
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                }
            });
        }

        public void cancelCollectionCourse(long courseId) {
            API.cancelCollectionCourse(this, courseId, new OkHttpListener<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse response) {
                    if (!isAttached()) return;
                    mViewRef.get().onCancelCollectionCourseSuccess();
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                    if (!isAttached()) return;
                    mViewRef.get().showToast(errorMessage);
                }
            });
        }

        public void collectionCourse(long courseId) {
            API.collectionCourse(this, courseId, new OkHttpListener<BaseResponse>() {
                @Override
                public void onSuccess(BaseResponse response) {
                    if (!isAttached()) return;
                    mViewRef.get().onCollectionCourseSuccess();
                }

                @Override
                public void onFailure(int errorCode, String errorMessage) {
                    if (!isAttached()) return;
                    mViewRef.get().showToast(errorMessage);
                }
            });
        }

        public void showCourseTextDialog(FragmentManager fragmentManager, CourseBean courseBean) {
            CourseDetailTextDialog dialog = new CourseDetailTextDialog.Builder()
                    .setGravity(Gravity.BOTTOM)
                    .setAnimation(R.style.SlideBottomAnimation)
                    .setSize(ViewGroup.LayoutParams.MATCH_PARENT, (int) (UIUtils.getScreenHeight() * 0.8))
                    .setCourseBean(courseBean)
                    .build();
            dialog.setDialogDismissListener(new DialogDismissListener() {
                @Override
                public void dismiss(DialogFragment dialog) {
                    mViewRef.get().onCourseTextDialogDismiss();
                }
            });
            dialog.show(fragmentManager, "CourseDetailTextDialog");
        }

        public void showCourseQuestionDialog(CourseDetailActivity courseDetailActivity, FragmentManager fragmentManager, CourseBean courseBean) {
            CourseDetailQuestionDialog dialog = new CourseDetailQuestionDialog.Builder()
                    .setGravity(Gravity.BOTTOM)
                    .setAnimation(R.style.SlideBottomAnimation)
                    .setSize(ViewGroup.LayoutParams.MATCH_PARENT, (int) (UIUtils.getScreenHeight() * 0.8))
                    .setCourseBean(courseBean)
                    .build();
            dialog.setDialogDismissListener(new DialogDismissListener() {
                @Override
                public void dismiss(DialogFragment dialog) {
                    mViewRef.get().onCourseTextDialogDismiss();
                }
            });
            dialog.show(fragmentManager, "CourseDetailTextDialog");
        }

        public void downloadCourse(String videoUrl) {
            // 文件名称MD5
            String mediaFileName = fileNameGenerator.generate(videoUrl);
            MusicFileBean musicFileBean = DBManager.getInstance().queryMusic(mediaFileName);
            File file = new File(Constant.CourseVideoDirectory, mediaFileName);
            if (file.exists() && musicFileBean.size == file.length()) {
                mViewRef.get().showToast("文件已下载");
            } else {
                String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                if (MPermission.hasPermissions(activity, permissions)) {
                    downloadFile(videoUrl, Constant.CourseVideoDirectory, mediaFileName);
                    mViewRef.get().onDownloadStart();
                } else {
                    MPermission.with(activity).permissions(permissions).request();
                }
            }
        }

        public void downloadFile(String url, String directory, final String fileName) {
            if (downloadBinder == null) {
                return;
            }
            downloadBinder.setDownloadCallBack(new SimpleDownloadCalback() {

                @Override
                public void getTotalSize(long size) {
                    MusicFileBean musicFileBean = DBManager.getInstance().queryMusic(fileName);
                    musicFileBean.size = size;
                    DBManager.getInstance().updateMusic(musicFileBean);
                }

                @Override
                public void onSuccess(String filePath) {
                    if (!isAttached()) return;
                    mViewRef.get().onDownloadSuccess(filePath);
                }

                @Override
                public void onFailed() {
                    if (!isAttached()) return;
                    mViewRef.get().showToast("下载失败");
                }
            });
            downloadBinder.startDownload(url, directory, fileName);
        }

        @Override
        public void detachView() {
            if (activity != null) {
                activity.unbindService(connection);
            }
            super.detachView();
        }
    }

}
